import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutterapp/common/util/log_utils.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';

/// 轮播组件
class BannerView<T> extends StatefulWidget {
  /// 数据集合
  final List<T> data;

  /// 外界传入页面组件
  final Widget Function(T t) child;

  /// 底部指示器的样式BasicIndicatorEffect
  final dynamic effect;

  /// 指示器在组件中的位置
  final AlignmentGeometry indicatorAlignment;

  /// 指示器的外边距
  final EdgeInsets indicatorMargin;

  /// 是否开启自动滑动
  final bool autoScroll;

  /// 自动滑动时间
  final Duration autoTime;

  /// 轮播组件
  const BannerView({
    Key? key,
    required this.data,
    required this.child,
    this.effect = const WormEffect(
      dotWidth: 8,
      dotHeight: 8,
    ),
    this.indicatorAlignment = Alignment.bottomCenter,
    this.autoScroll = true,
    this.autoTime = const Duration(seconds: 3),
    this.indicatorMargin = const EdgeInsets.all(0),
  }) : super(key: key);

  @override
  _BannerViewState createState() => _BannerViewState<T>();
}

class _BannerViewState<T> extends State<BannerView<T>> {
  /// 页面控制器
  late PageController _pageController;

  /// 时间控制器
  Timer? _timer;

  /// 当前页面
  int _currentPage = 0;

  /// 实际需要的数据源
  List<T> children = [];

  @override
  void initState() {
    super.initState();

    _pageController = PageController();
    _pageController.addListener(() {});
  }

  @override
  void didUpdateWidget(covariant BannerView<T> oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (widget.data.length > 0) startScroll();
  }

  /// 开始滑动
  void startScroll() {
    if (!widget.autoScroll) return;
    if (_timer?.isActive ?? false) return;
    if (widget.data.length <= 1) return;
    _createTimer();
  }

  /// 停止滑动
  void stopScroll() {
    if (!widget.autoScroll) return;
    _cancelTimer();
  }

  /// 创建定时器
  void _createTimer() {
    if (widget.autoScroll) {
      _cancelTimer();
      _timer = Timer.periodic(widget.autoTime, (timer) {
        //滑动到下一个页面
        _scrollNextPage();
      });
    }
  }

  /// 取消定时器
  void _cancelTimer() {
    _timer?.cancel();
  }

  /// 滑动到下一个页面
  void _scrollNextPage() {
    _currentPage++;
    int next = _currentPage % widget.data.length;
    _pageController.animateToPage(
      next,
      duration: Duration(milliseconds: 600),
      curve: Curves.ease,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return widget.data.length == 0
        ? Container()
        : Container(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: Listener(
              onPointerDown: (tapDown) {
                LogUtils.d('手指按下,停止滑动');
                //手指按下
                stopScroll();
              },
              onPointerUp: (tapUP) {
                LogUtils.d('手指抬起,开始滑动');
                //手指抬起
                startScroll();
              },
              child: Stack(
                alignment: widget.indicatorAlignment,
                children: [
                  //viewpage
                  PageView.builder(
                    itemCount: widget.data.length,
                    controller: _pageController,
                    itemBuilder: (BuildContext context, int index) {
                      return widget.child.call(widget.data[index]);
                    },
                  ),
                  //viewpage指示器
                  Padding(
                    padding: widget.indicatorMargin,
                    child: SmoothPageIndicator(
                      controller: _pageController,
                      count: widget.data.length,
                      axisDirection: Axis.horizontal,
                      effect: widget.effect,
                    ),
                  ),
                ],
              ),
            ),
            height: 180.0,
          );
  }
}
